package com.yaps.petstore.managedbean;


import com.yaps.barkbank.validator.Validation;
import com.yaps.petstore.entity.catalog.Item;
import com.yaps.petstore.entity.customer.Customer;
import com.yaps.petstore.entity.order.CreditCard;
import com.yaps.petstore.entity.order.Order;

import com.yaps.petstore.dto.CartItem;
import com.yaps.petstore.entity.customer.Address;


import com.yaps.petstore.exception.CreditCardException;
import com.yaps.petstore.service.CatalogService;
import com.yaps.petstore.service.OrderService;
//import com.yaps.petstore.service.OrderService;
import com.yaps.petstore.service.ShoppingCartService;
//import com.yaps.barkbank.validator.ValidationService;
//import com.yaps.barkbank.validator.Validation;

import javax.xml.ws.WebServiceRef;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Antonio Goncalves
 */
@Scope("session")
@Component("cart")
public class ShoppingCartController extends Controller {

    // ======================================
    // =             Attributs              = 
    // ======================================
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private OrderService orderService;

    private final String cname = this.getClass().getName();

    private CreditCard creditCard = new CreditCard();
    // Customer et Address sont initialisés par le faces-config.xml dans l'ancienne version 
    private Customer customer;
    private Address deliveryAddress = new Address();
    private Order order;
    
    @Autowired
    private Validation validator;
    
    @Autowired
    private AccountController accountController;
    
    
    public ShoppingCartController()
    {
       
    }
    
    // ======================================
    // =          Methodes publiques        =
    // ======================================

    public String addItemToCart() {
        final String mname = "addItemToCart";
        logger.entering(cname, mname);

        String navigateTo = null;

        try {
            Item item = catalogService.findItem(getParamId("itemId"));
            shoppingCartService.addItem(item);
            navigateTo = "/showcart.jsf?faces-redirect=true";
        } catch (Exception e) {
            addMessage(cname, mname, e);
        }

        logger.exiting(cname, mname, navigateTo);
        return navigateTo;
    }

    public String removeItemFromCart() {
        final String mname = "removeItemFromCart";
        logger.entering(cname, mname);

        String navigateTo = "/showcart.jsf?faces-redirect=true";

        try {
            Item item = catalogService.findItem(getParamId("itemId"));
            shoppingCartService.removeItem(item);
        } catch (Exception e) {
            addMessage(cname, mname, e);
        }

        logger.exiting(cname, mname, navigateTo);
        return navigateTo;
    }

    public String updateQuantity() {
        final String mname = "updateQuantity";
        logger.entering(cname, mname);

        String navigateTo = "/showcart.jsf?faces-redirect=true";

        logger.exiting(cname, mname, navigateTo);
        return navigateTo;
    }

    public String checkout() {
        final String mname = "checkout";
        logger.entering(cname, mname);

        String navigateTo = "/confirmorder.jsf?faces-redirect=true";
        this.customer = accountController.getCustomer();
        this.deliveryAddress = accountController.getHomeAddress();
        
        logger.exiting(cname, mname, navigateTo);
        return navigateTo;
    }

    public String confirmOrder() {
        final String mname = "confirmOrder";
        logger.entering(cname, mname);

        String navigateTo = null;

        try {
            // Calls the web service to validate the credit card
            validateCreditCard(creditCard);
            order = orderService.createOrder(customer, deliveryAddress, creditCard, shoppingCartService.getCartItems());
            shoppingCartService.empty();
            navigateTo = "/orderconfirmed.jsf?faces-redirect=true";
        } catch (Exception e) {
            addMessage(cname, mname, e);
        }

        logger.exiting(cname, mname, navigateTo);
        return navigateTo;
    }

    public Float getTotal() {
        return shoppingCartService.getTotal();
    }

    public List<CartItem> getCartItems() {
        return shoppingCartService.getCartItems();
    }

    // ======================================
    // =             Accesseurs             =
    // ======================================

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Address getDeliveryAddress() {
        return deliveryAddress;
    }

    public void setDeliveryAddress(Address deliveryAddress) {
        this.deliveryAddress = deliveryAddress;
    }

    public CreditCard getCreditCard() {
        return creditCard;
    }

    public void setCreditCard(CreditCard creditCard) {
        this.creditCard = creditCard;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    // ======================================
    // =           Methodes Privées         =
    // ======================================

    private void validateCreditCard(CreditCard creditCard) {
        String statusCard;

        
        statusCard = validator.validateCard(creditCard.getCreditCardNumber(),
                creditCard.getCreditCardType(),
                creditCard.getCreditCardExpDate());
        logger.info("Validation Service has been called. isCardValid=" + statusCard);

        if (!"OK".equals(statusCard))
            throw new CreditCardException("Credit Card is invalid : " + statusCard);

    }
}
